package com.manage.oauth.controller;

import com.manage.common.core.constants.Constant;
import com.manage.common.core.enums.GrantType;
import com.manage.common.core.result.JsonResult;
import com.manage.oauth.dto.Oauth2TokenDto;
import lombok.AllArgsConstructor;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.security.Principal;
import java.util.Map;

/**
 * 自定义Oauth2获取令牌接口
 *
 * @author zq
 * @date 2020/7/17
 */
@AllArgsConstructor
@RestController
@RequestMapping("/oauth")
public class AuthController {

    private final TokenEndpoint tokenEndpoint;

    /**
     * Oauth2获取token
     */
    @PostMapping(value = "/token")
    public JsonResult postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
        OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
        String refreshToken = null;
        // 如果授权模式为密码模式,设置刷新tonken
        if (parameters.get(Constant.GRANT_TYPE).equals(GrantType.PASSWORD.getCode()) ||
                parameters.get(Constant.GRANT_TYPE).equals(GrantType.REFRESH_TOKEN.getCode())) {
            assert oAuth2AccessToken != null;
            refreshToken = oAuth2AccessToken.getRefreshToken().getValue();
        }
        // 刷新token模式，返回的新的刷新token,在初始化tokenService时候没有选择每次新生成token,则每次返回的刷新token没有写到redis里面,需要返回原刷新token
        if(parameters.get(Constant.GRANT_TYPE).equals(GrantType.REFRESH_TOKEN.getCode())){
            refreshToken = parameters.get(GrantType.REFRESH_TOKEN.getCode());
        }
        assert oAuth2AccessToken != null;
        Oauth2TokenDto oauth2TokenDto = Oauth2TokenDto.builder()
                .token(oAuth2AccessToken.getValue())
                .refreshToken(refreshToken)
                .expiresIn(oAuth2AccessToken.getExpiresIn())
                .tokenHead(Constant.JWT_TOKEN_PREFIX).build();

        return JsonResult.success(oauth2TokenDto);
    }
}
